package com.hexiang.error;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice(annotations = ResponseBody.class)
public class ErrorHandler {
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public Map<String,String> handleServiceException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();

        Map map=new HashMap();
        map.put("errCode","100029");
        map.put("errMsg",message);
        return map;
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String,String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> objectErrorList = e.getBindingResult().getAllErrors();
        String message =  objectErrorList.get(0).getDefaultMessage();
        Map map=new HashMap();
        map.put("errCode","100029");
        map.put("errMsg",message);
        return map;
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String,String> exception(Exception e) {
        Map map=new HashMap();
        map.put("errCode","100029");
        map.put("errMsg",e.getMessage());
        return map;
    }
}
